"use client";

import useSCIM from "@/lib/swr/use-scim";
import useWorkspace from "@/lib/swr/use-workspace";
import { useRemoveSCIMModal } from "@/ui/modals/remove-scim-modal";
import { useSCIMModal } from "@/ui/modals/scim-modal";
import { ThreeDots } from "@/ui/shared/icons";
import { Button, IconMenu, Popover, TooltipContent } from "@dub/ui";
import { SAML_PROVIDERS } from "@dub/utils";
import { FolderSync, ShieldOff } from "lucide-react";
import { useMemo, useState } from "react";

export function SCIM() {
  const { plan } = useWorkspace();
  const { SCIMModal, setShowSCIMModal } = useSCIMModal();
  const { RemoveSCIMModal, setShowRemoveSCIMModal } = useRemoveSCIMModal();

  const { provider, configured, loading } = useSCIM();

  const data = useMemo(() => {
    if (loading) {
      return {
        logo: null,
        title: null,
        description: null,
      };
    } else if (configured) {
      return {
        logo: (
          <img
            src={SAML_PROVIDERS.find((p) => p.scim === provider)!.logo}
            alt={`${provider} logo`}
            className="h-8 w-8"
          />
        ),
        title: `${SAML_PROVIDERS.find((p) => p.scim === provider)!.name} SCIM`,
        description: "SCIM directory sync is configured for your workspace.",
      };
    } else
      return {
        logo: (
          <div className="rounded-full border border-neutral-200 p-2">
            <FolderSync className="h-4 w-4 text-neutral-600" />
          </div>
        ),
        title: "SCIM",
        description: "Choose an identity provider to get started.",
      };
  }, [provider, configured, loading]);

  const [openPopover, setOpenPopover] = useState(false);

  return (
    <>
      {configured ? <RemoveSCIMModal /> : <SCIMModal />}
      <div className="rounded-xl border border-neutral-200 bg-white">
        <div className="relative flex flex-col gap-5 p-5">
          <div className="flex flex-col gap-1">
            <h2 className="text-base font-medium text-neutral-900">
              Directory Sync
            </h2>
            <p className="text-sm text-neutral-500">
              Automatically provision and deprovision users from your identity
              provider.
            </p>
          </div>

          <div className="rounded-xl border border-neutral-200 bg-white">
            <div className="flex flex-col items-start justify-between space-y-4 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:space-y-0">
              <div className="flex flex-col items-start gap-4 sm:flex-row sm:items-center">
                {data.logo || (
                  <div className="h-8 w-8 animate-pulse rounded-full bg-neutral-100" />
                )}
                <div className="flex flex-col">
                  {data.title ? (
                    <h3 className="font-medium">{data.title}</h3>
                  ) : (
                    <div className="h-5 w-20 animate-pulse rounded-md bg-neutral-100" />
                  )}
                  {data.description ? (
                    <p className="text-sm text-neutral-500">
                      {data.description}
                    </p>
                  ) : (
                    <div className="mt-2 h-4 w-40 animate-pulse rounded-md bg-neutral-100" />
                  )}
                </div>
              </div>
              <div>
                {loading ? (
                  <div className="h-9 w-24 animate-pulse rounded-md bg-neutral-100" />
                ) : configured ? (
                  <Popover
                    content={
                      <div className="grid w-full gap-1 p-2 sm:w-48">
                        <button
                          onClick={() => {
                            setShowSCIMModal(true);
                            setOpenPopover(false);
                          }}
                          className="rounded-md p-2 text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
                        >
                          <IconMenu
                            text="View configuration"
                            icon={<FolderSync className="h-4 w-4" />}
                          />
                        </button>
                        <button
                          onClick={() => {
                            setShowRemoveSCIMModal(true);
                            setOpenPopover(false);
                          }}
                          className="rounded-md p-2 text-left text-sm font-medium text-red-600 transition-all duration-75 hover:bg-red-600 hover:text-white"
                        >
                          <IconMenu
                            text="Remove"
                            icon={<ShieldOff className="h-4 w-4" />}
                          />
                        </button>
                      </div>
                    }
                    align="end"
                    openPopover={openPopover}
                    setOpenPopover={setOpenPopover}
                  >
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenPopover(!openPopover);
                      }}
                      className="rounded-md px-1 py-2 transition-all duration-75 hover:bg-neutral-100 active:bg-neutral-200"
                    >
                      <span className="sr-only">Edit</span>
                      <ThreeDots className="h-5 w-5 text-neutral-500" />
                    </button>
                  </Popover>
                ) : (
                  <Button
                    text="Configure"
                    disabled={plan !== "enterprise"}
                    {...(plan !== "enterprise" && {
                      disabledTooltip: (
                        <TooltipContent
                          title="SCIM Directory Sync is only available on Enterprise plans. Upgrade to get started."
                          cta="Contact sales"
                          href="https://dub.co/enterprise"
                          target="_blank"
                        />
                      ),
                    })}
                    onClick={() => setShowSCIMModal(true)}
                  />
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="rounded-b-xl border-t border-neutral-200 bg-neutral-50 px-5 pb-4 pt-3">
          <a
            href="https://dub.co/help/category/saml-sso"
            target="_blank"
            className="text-sm text-neutral-400 underline underline-offset-4 transition-colors hover:text-neutral-700"
          >
            Learn more about SCIM Directory Sync
          </a>
        </div>
      </div>
    </>
  );
}
